<template>
  <section>
    <!--工具条：高级查询 + 新增-->
    <!--:inline="true"  行内表单:占一排-->

    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" >新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--
      :data="products" - 列表数据
      highlight-current-row v-loading="listLoading" - 当前行高亮
      @selection-change="selsChange" - 选项改变就是触发
      v-loading="listLoading" - 记载框
    -->
    <el-table :data="products" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-else style="color: green">上架</span>
        </template>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100" sortable>
      </el-table-column>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" :disabled="scope.row.state!=0">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" :disabled="scope.row.state!=0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除 + 分页栏-->
    <el-col :span="24" class="toolbar">
      <!--
        :disabled="this.sels.length===0"
        当sels长度为0的时候，显示当前属性disabled - 禁用。如果不为0就不禁用
       -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" >批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <!--
      title="添加或修改" - 标题
      :visible.sync="saveFormVisible" - 控制当前对话框是否显示 - 默认为false不显示
      :close-on-click-modal="false" - 点击对话框以外的区域不关闭
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <!--
        :model="saveForm"  - 表单绑定模型数据对象saveForm
        label-width="80px"  - 标签的宽度
        :rules="saveFormRules" - 验证规则 - 表单项校验
        ref="saveForm" - 为当前对话框取名saveForm - 做表单校验

        label="姓名" - 标签名字
        prop="name" - 要做校验的时候必须要，不做校验就没有必要
        v-model="saveForm.name" - 双向绑定
        auto-complete="off" - 自动完成 - 关闭
      -->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称"  prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"  ></el-input>
        </el-form-item>
        <el-form-item label="成本价" >
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" >
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <!--
             action=调用我们的上传接口
             我们配置了axios基础路径，为啥还要写上http://localhost:8080？ - 这里不是axios发送的请求
              :on-remove="handleRemove" - 删除成功之后的回调
              :on-success="handleSuccess" - 上传成功之后的回调
              :file-list="fileList" - 文件列表 - 上传一个文件不用管
          -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="销售数量" >
          <el-input v-model="saveForm.salecount" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.productDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>/
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {
  getProductListPage,
  removeProduct,
  batchRemoveProduct,
  editProduct,
  addProduct
} from '../../api/api';

//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //文件上传列表 - 资源resources
      fileList:[],

      quillOption: quillConfig,
      //1.分页查询的相关参数
      products: [],  //列表数据
      pageSize: 5,      //每页显示的条数
      currentPage: 1,   //当前页
      totals: 0,        //总数量
      listLoading: false, //加载框


      //2.高级查询的相关参数
      keyword: '',

      //3.批量删除的相关数据
      sels: [],//列表选中列

      //4.添加或修改的相关数据
      title:'',
      saveFormVisible: false, //控制对话框是否显示 - 默认不显示
      saveLoading: false,     //保存的加载框 - 默认不显示
      saveFormRules: {        //表单项验证
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ]
      },

      //添加和修改中对话框的数据
      saveForm: {
        id: null,
        name: '',
        costprice: null,
        saleprice:null,
        resources: '' ,
        salecount: null,
        state: 1,
        offsaletime: '',
        onsaletime: '',
        createtime: '',
        ProductDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },
      //显示所有的部门经理
      types: [],
      //显示所属角色
      roles: [],
      managers: []
    }
  },
  methods: {
    //1.获取部门列表
    getProducts() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true; //显示加载框
      this.$http.post("/product", para).then(res => {
        this.products = res.data.data;//给数组赋值 - 显示列表数据
        this.totals = res.data.totals;  //给总数量赋值 - 计算分页栏
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试");
      })
    },

    //2.点击分页实现
    //val  的值就是页数  所以 this.currentPage = val;
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProducts();
    },


    //3.高级查询 = 关键字查询
    keywordQuery(){
      //防止当前页不在第一页的时候 通过关键字查询出现 当前页没有数据的情况 this.currentPage = 1;
      this.currentPage = 1;
      this.getProducts();
    },

    //4.删除功能逻辑
    handleDel: function (index, row) {
      //elementUi提供确认框 - 点确定之后执行then里面的代码，点击取消执行catch中的逻辑
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.delete("/product/"+row.id).then(res=>{
          this.listLoading = false; //关闭加载框
          if(res.data.success){
            this.$message.success("删除成功"); //提示成功消息
            //删除成功之后 对当前页的处理【特殊情况：删除最后一页的最后一条数据】
            var totalPage = Math.ceil(this.totals/this.pageSize);
            if (this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getProducts();
          }else{
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },

    //5.选项改变的时候触发的逻辑
    selsChange: function (sels) {
      //将选中的对象的数组  赋值给 模型数据sels
      this.sels = sels;
    },

    //6.批量删除逻辑
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/product",ids).then(res=>{
          this.listLoading = false; //隐藏加载框
          if(res.data.success){ //操作成功
            this.currentPage = 1;
            this.getProducts();
          }else{ //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },

    //7.点击修改按钮弹出对话框
    handleEdit: function (index, row) {
      this.title = "编辑";
      //弹出对话框
      this.saveFormVisible = true;
      //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
      this.saveForm = Object.assign({}, row);
      //获取所有的经理
      //获取所属角色
      this.getRoles();
      //处理fileList
      this.fileList=[];
      if(this.saveForm.resources){
        // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length ; i++) {
          var url = arr[i]
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },

    //8.点击新增按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        costprice: null,
        saleprice:null,
        typeId: null,
        resources: '' ,
        state: 1,
        shopId: null,
        userId: null,
        searchMasterMsgId: null,
        productDetail:{  //与后端实体类一致
          intro: '',
        }
      };
      //获取所有的经理
      //获取所属角色
      this.getRoles();
      this.fileList = [];
    },

    //9.点击保存提交数据到后端
    saveSubmit: function () {
      //表单验证：只要表单项中任何一个验证不通过，都不能点击提交
      //所有的ref中名称为saveForm的表单
      this.$refs.saveForm.validate((valid) => {
        if (valid) { //表单验证通过 => 每一个表单项都通过了
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true; //显示加载框
            let para = Object.assign({}, this.saveForm);

            var isArr = para.typeId;
            if(Array.isArray(isArr)){
              if(isArr.length==0){//空数组
                para.typeId = null;
              }else{
                para.typeId = isArr[isArr.length - 1];
              }
            }
            this.$http.put("/product",para).then(res=>{
              this.saveLoading = false;  //关闭加载框
              this.saveFormVisible = false; //关闭对话框
              if(res.data.success){
                this.getProducts();//重新加载新的数据
              }else{
                this.$message.error("系统繁忙，请稍后重试!!![500]");
              }
            }).catch(res=>{
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
            })
          });
        }
      });
    },

    //10.获取所有的角色
    getRoles(){
      this.$http.get("/shop").then(res=>{
        this.managers = res.data;
      })
    },
    //12.文件上传的业务逻辑
    handleSuccess(response, file, fileList){
      // /group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
      var url = response.obj;// /group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
      //如果resources='',加了一张图片，resources='url'。如果是多张图片，resources='url1,url2'[js中认为''，null都是false]
      //1.处理resource：添加和修改都要考虑
      if(this.saveForm.resources){
        this.saveForm.resources = this.saveForm.resources+","+url;
      }else{
        this.saveForm.resources = url;
      }
      //再进行处理fileList
      this.fileList = [];
      if(this.saveForm.resources){
        // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i]
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },

    //13.文件删除的业务逻辑
    handleRemove(file, fileList) {
      var filePath =file.url;
      filePath = filePath.substring(filePath.indexOf("/group1"));


      this.$http.delete("/fastDfs?path="+filePath).then(res=>{
        if(res.data.success){
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        }else{
          this.$message({
            message: '删除失败!',
            type: 'error'
          });
        }
      })

      //1.处理resources 假如resources="url1,url2,url3,url4",现在删除一张图片url2。resources="url1,url3,url4"
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i];
          //循环遍历 找出删除图片的url
          if(url == filePath){
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(",");
      }
      //2.处理fileList
      this.fileList = [];
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i]
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //14.上架
    onsale(){
      if(this.sels.length<1){
        this.$message.warning("请选择宠物之后再上架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要上架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/onsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.getProducts();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },
    offsale(){
      if(this.sels.length<1){
        this.$message.warning("请选择宠物之后再下架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要下架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/offsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.getProducts();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },
  },
  //页面加载的时候就出现表格数据
  mounted() {
    this.getProducts();
  }
}
</script>

<style scoped>

</style>